<template>
  <div id="app">
    <input type="text" v-model="value" name="" id="" />
    <button @click="onSearch">搜索</button>
    <h1>历史搜索</h1>
    <div class="search-list">
      <span @click="onClickSearch(item)" v-for="item in historyArr" :key="item">
        {{ item }}
      </span>
    </div>
    <hr />
    <ul>
      <li class="list-item" v-for="item in list" :key="item.id">
        {{ item.goodsName }}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'App',
  components: {},
  data() {
    return {
      opt: {
        page: 1,
        size: 10,
      },
      value: '',
      list: [],
      historyArr: JSON.parse(localStorage.getItem('historyArr')) || [], // 最近搜索
      hotHistoryArr: [], // 热门搜索
    }
  },
  watch: {
    value(newVal) {
      // if (newVal) {
      //   this.getSearchFunc(newVal)
      // } else {
      //   this.getData()
      // }
    },
  },
  created() {
    this.getData()
  },
  computed: {},
  methods: {
    async getData() {
      const res = await axios.get('/api/list', { params: this.opt })
      console.log(res.data.data.list)
      this.list = res.data.data.list
    },
    // 点击搜索记录去搜索
    onClickSearch(value) {
      this.getSearchFunc(value)
    },
    getSearchFunc(newVal) {
      console.log('newVal:', newVal)
      // if (newVal) {
      this.list = this.list.filter((v) => {
        if (v.goodsName.includes(newVal)) {
          return v
        }
      })
      // }
      console.log(this.list, '------------------')
    },
    onSearch() {
      console.log('this.value:', this.value)
      // 去重之后，放在数组中
      if (this.value && this.historyArr.indexOf(this.value) === -1) {
        // 搜索函数
        console.log(this.value, '搜索')
        this.getSearchFunc(this.value)
        this.historyArr.push(this.value)
        localStorage.setItem('historyArr', JSON.stringify(this.historyArr))
        this.value = ''
      } else {
        this.getData()
      }

      console.log(this.historyArr, 'historyArr')
    },
  },
}
</script>

<style lang="scss">
* {
  margin: 0;
  padding: 0;
  list-style: none;
}
.search-list {
  span {
    padding: 5px;
    margin: 5px;
    display: inline-block;
    border: 1px solid #ccc;
    border-radius: 5px;
  }
}
.list-item {
  padding: 5px;
  margin: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
}
</style>
